<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2012 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class wxapi_response {

    public $token = "";
    public $member_auth = array();
    public function __construct(&$app)
    {
        $this->_request = kernel::single('base_component_request');
        $this->_response = kernel::single('base_component_response');
        
        //$this->check_sign();
        
        $this->user_auth();
    }
    
    //这里有漏洞，除了time之外的参数没有参与签名
    public function check_sign()
    {
        $data = $this->_request->get_params(true);
        
        $sign = $data['sign'];
        $time = $data['time'];
        $local_sign = md5($time. constant('WX_REQUEST_TOKEN'));
        if($sign != $local_sign){
            self::api_error('sign error');
        }

        //单次请求五分钟有效
        if(!constant('TEST_MODE') && (date('YmdHis') - $time) > 60*5){
            self::api_error('request timeout');
        }
    }
    
    //检查用户身份，将token转换成member_id
    public function user_auth()
    {
        //return array('member_id'=>10);
        $openid = $_GET['openId'] ? $_GET['openId'] : $_POST['openId'];
        if( ! $openid or strlen($openid) < 16 or constant('TEST_MODE') ) {
            //$openid = 'oeJKo5Z_ABFI7E_b5vYIR2THA-1o';
        }
        
        //身份验证
        if($openid){
            //登录，设置session cookies
            //手动指定sess_id
            $_GET['sess_id'] = md5($openid.'shopex123');
            kernel::single('base_session')->start();
            $this->userObject = kernel::single('b2c_user_object');
            //$this->userPassport = kernel::single('b2c_user_passport');
            
            $mdl_pam_members = app::get('pam')->model('members');
            $rs_member = $mdl_pam_members->dump(array('login_account' => $openid));
            $member_id = $rs_member['member_id'];
            
            $this->userObject->set_member_session($member_id);
            $this->bind_member($member_id);
            
            $this->member_info = $rs_member;
            return $rs_member;
        }
        return false;
    }
    
    public function bind_member($member_id)
    {
        $columns = array(
            'account'=> 'member_id,login_account,login_password',
            'members'=> 'member_id,member_lv_id,cur,lang,name',
        );
        $userObject = kernel::single('b2c_user_object');
        $cookie_expires = $userObject->cookie_expires ? time() + $userObject->cookie_expires * 60 : 0;
        $data = $userObject->get_members_data($columns);
        $secstr = kernel::single('b2c_user_passport')->gen_secret_str($member_id, $data['account']['login_name'], $data['account']['login_password']);
        //$login_name = $userObject->get_member_name($data['account']['login_name']);
        $this->cookie_path = kernel::base_url().'/';
        #$this->set_cookie('MEMBER',$secstr,0);
        
        //$this->set_cookie('UNAME',$login_name,$cookie_expires);
        $this->set_cookie('UNAME',$data['members']['name'],$cookie_expires);
        
        $this->set_cookie('MLV',$data['members']['member_lv_id'],$cookie_expires);
        $this->set_cookie('CUR',$data['members']['cur'],$cookie_expires);
        $this->set_cookie('LANG',$data['members']['lang'],$cookie_expires);
        $this->set_cookie('S[MEMBER]',$member_id,$cookie_expires);
    }
    
    function set_cookie($name,$value,$expire=false,$path=null)
    {
        if(!$this->cookie_path){
            $this->cookie_path = kernel::base_url().'/';
            #$this->cookie_path = substr(PHP_SELF, 0, strrpos(PHP_SELF, '/')).'/';
            #$this->cookie_life =  $this->app->getConf('system.cookie.life');
        }
        $this->cookie_life = $this->cookie_life > 0 ? $this->cookie_life : 315360000;
        $expire = $expire === false ? time()+$this->cookie_life : $expire;
        setcookie($name,$value,$expire,$this->cookie_path);
        $_COOKIE[$name] = $value;
    }
    
    static public function api_error($message = '', $code = 1)
    {
        return self::return_json([
            'code' => $code ? : 1,
            'msg' => $message ? : '服务器正忙，请稍后再试',
        ]);
    }
    
    static public function api_success($data = array())
    {
        return self::return_json([
            'code' => 0,
            'msg' => '',
            'data'=>$data,
        ]);

    }

    static public function return_json($data = array()) 
    {
        if(is_array($data)){
            echo(json_encode($data));
        } else {
            echo($data);
        }
        exit;
    }

    static public function Dump($arr){
        echo "<pre>";
        print_r($arr);die;
    }
}
